mod  routers;
mod  middleware;
mod  state;

use std::{net::SocketAddr, sync::Arc};
use std::collections::HashSet;
use std::sync::Mutex;


use axum::{
    extract::Extension,
    http::{HeaderValue, Method,StatusCode},
    handler::Handler, Router,
    routing::get,
    response::IntoResponse,
};

use tower_http::cors::CorsLayer;
use serde_json::json;
use routers::{get_router, ws::ws_handler};
use middleware::{db::get_pool, response::MyResponse, https::get_https_client};
use  state::AppState;

use tokio::sync::broadcast;




#[tokio::main]
async fn main()-> anyhow::Result<()> {

    //数据库连接池
    let pool = get_pool().await;
    //服务器端请求
    let client =get_https_client();
    //
    let send_catch =  Mutex::new(HashSet::new());
    //
    let (tx, _rx) = broadcast::channel(100);
    //共享变量
    let state = Arc::new(AppState { send_catch, tx });

    let app = Router::new()
        .route("/ws", get(ws_handler))
        .merge(get_router())
        .layer(Extension(client)) //客户端发送
        .layer(Extension(pool)) //数据库
        .layer(Extension(state))//公共状态
        .layer(
            CorsLayer::new()
            .allow_origin("http://127.0.0.1:3000".parse::<HeaderValue>()?)//跨域
            .allow_methods([Method::GET,Method::POST,Method::PUT]),
        );//跨域

    let app = app.fallback(handler_404.into_service()); //全局404

    let addr = SocketAddr::from(([192,168,1,114], 8000));
    // tracing::debug!("listening on {}", addr);
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await?;
    Ok(())
}


async fn handler_404() -> impl IntoResponse {
    (StatusCode::OK,MyResponse::NotFound(json!("notfound")).into())
}
